// src/modules/auth/models/AuthModel.ts
import { types, flow, Instance } from "mobx-state-tree";
import { loginApi } from "../services/authApi";

// 认证模型定义
export const AuthModel = types
  .model("AuthModel", {
    token: types.maybe(types.string),
    userId: types.maybe(types.string),
    isLoading: false,
    error: types.maybe(types.string),
  })
  .actions((self) => ({
    login: flow(function* (email: string, password: string) {
      self.isLoading = true;
      self.error = undefined;
      
      try {
        // 模拟API调用
        const response: any = yield loginApi(email, password);
        self.token = response.token;
        self.userId = response.userId;
        self.isLoading = false;
        return { success: true };
      } catch (error: any) {
        self.isLoading = false;
        self.error = error.message;
        return { success: false, error: error.message };
      }
    }),
    
    logout: () => {
      self.token = undefined;
      self.userId = undefined;
    },
    
    setError: (error: string) => {
      self.error = error;
    },
  }))
  .views((self) => ({
    get isAuthenticated() {
      return !!self.token;
    },
  }));

export type AuthModelInstance = Instance<typeof AuthModel>;